DataTableTemplate = DataTableTemplate or Class("DataTableTemplate")

---@diagnostic disable-next-line: duplicate-set-field
function DataTableTemplate:ctor(dataManager)
    self._dataManager = dataManager
    self._dataSettings = {}
    self._formulaArgs = {}
    self._dataTables = {}
    self._dic = {}
    self.id = dataManager:createInstanceId()
end

function DataTableTemplate:createDataTable()
    local dt = DataTable.new(self, self._dataManager)
    for id, setting in pairs(self._dataSettings) do
        if setting.dataType == DataType.DeriveNumber then
            dt:setDirty(id)
        end
    end
    table.insert(self._dataTables, dt)
    self._dic[dt.id] = dt
    return dt
end

function DataTableTemplate:getDataTable(id)
    return self._dic[id]
end

function DataTableTemplate:addNumber(number)
    local setting = {
        dataType = DataType.Number,
        defaultValue = number,
    }
    return self:_addData(setting).id
end

function DataTableTemplate:addDeriveNumber()
    local setting = {
        dataType = DataType.DeriveNumber,
        formula = {}
    }
    return self:_addData(setting).id
end

function DataTableTemplate:addDataTable(templateId)
    local setting = {
        dataType = DataType.DataTable,
        templateId = templateId,
        defaultValue = 0
    }
    return self:_addData(setting).id
end

function DataTableTemplate:_addData(setting)
    setting.id = self._dataManager:createPropId()
    self:loadData(setting)
    for i, dt in ipairs(self._dataTables) do
        dt:addData(setting)
    end
    return setting
end

-- 载入数据设置
function DataTableTemplate:loadData(setting)
    self._dataSettings[setting.id] = setting
end
function DataTableTemplate:subscribe(dataId, srcPath)
    if not self._subscribes[dataId] then
        self._subscribes[dataId] = {}
    end
    self._subscribes[dataId][srcPath] = true
end

function DataTableTemplate:addFormulaArg(dataId, argPath, rootSelf, defaultValue)
    local argId = self._dataManager:createArgId()
    local arg = {
        dataId = dataId,
        argId = argId,
        argPath = type(argPath) == "table" and argPath or {argPath},
        rootSelf = rootSelf,
        defaultValue = defaultValue or 0
    }
    self._formulaArgs[argId] = arg
    for _, v in ipairs(self._dataTables) do
        v:addFormulaArg(arg)
    end
    return argId
end

function DataTableTemplate:setFormula(dataId, calculator)
    self._dataSettings[dataId].calculator = calculator
    for _, v in ipairs(self._dataTables) do
        v:setDirty(dataId)
    end
end

function DataTableTemplate:getArgInfo(argId)
    return self._formulaArgs[argId]
end